/* Copyright (c) 2010 OFXKit
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#import "OFXDocumentRequest.h"
#import "OFXRequest.h"

@implementation OFXDocumentRequest

@synthesize messageSets;
@synthesize signOnRequest;

- (id)initWithVersion:(NSString*)requestOfxVersion
{
  self = [super init];

  self.messageSets = [[NSMutableArray alloc] init];
  
  [self setOfxVersion:requestOfxVersion];
  [self setSecurity:@"NONE"];
  [self setEncoding:@"USASCII"];
  [self setCharset:@"1252"];
  [self setCompression:@"NONE"];
  [self setFileUIDNew:@"NONE"];
  [self setFileUIDOld:[OFXObject stringWithUUID]];
  
  return self;
}

- (NSString*)asString
{
  NSMutableString* result = [NSMutableString stringWithCapacity:DEFAULT_DOCUMENT_LENGTH];
  
  // create the document header
  if ([[self ofxVersion] intValue] < 200) {
    // OFX 1.x header
    [result appendFormat:@"OFXHEADER:100\r\n"
                          "DATA:OFXSGML\r\n"
                          "VERSION:%@\r\n"
                          "SECURITY:%@\r\n"
                          "ENCODING:%@\r\n"
                          "CHARSET:%@\r\n"
                          "COMPRESSION:%@\r\n"
                          "OLDFILEUID:%@\r\n"
                          "NEWFILEUID:%@\r\n\r\n", 
     ofxVersion, security, encoding, charset, compression, fileUIDOld, 
     fileUIDNew];
  } else {
    // OFX 2.x header
    [result appendFormat:@"<?xml version=\"1.0\"?><?OFX OFXHEADER=\"200\" "
                          "VERSION=\"%@\" SECURITY=\"%@\" OLDFILEUID=\"%@\" "
                          "NEWFILEUID=\"%@\"?>", ofxVersion, security, 
     compression, fileUIDOld, fileUIDNew];
  }  
  
  [result appendString:@"<OFX>"];
  int version = [ofxVersion intValue];
  
  // first message set has to be SONRQ
  if (signOnRequest != nil) {
    [result appendString:[signOnRequest formRequestForOFXVersion:version]];
  }
  
  // serialize message sets
  for (OFXObject<OFXRequest>* messageSet in messageSets) {
    [result appendString:[messageSet formRequestForOFXVersion:version]];
  }
  
  [result appendString:@"</OFX>"];
  
  return result;
}

@end
